package com.dualsportmaps.android.activities;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import net.osmand.plus.OsmandSettings;
import net.osmand.plus.activities.OsmandApplication;
import net.osmand.plus.activities.SettingsActivity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;
import android.widget.ListView;
import android.widget.Toast;

import com.dualsportmaps.android.DsmMapDownload;
import com.dualsportmaps.android.DsmResourceManager;
import com.dualsportmaps.android.IDsmMapDownloadListener;
import com.dualsportmaps.android.R;

public class SearchDSMActivity extends ListActivity implements IDsmMapDownloadListener {
//	private final static Log log = LogUtil.getLog(SearchDSMActivity.class);
	DsmResourceManager dsmResourceManager; 
	boolean showActiveOnly = false;
	HashMap<String,DsmMapDownload> baseList;
	public static String title = "Search Results";
	@Override
	public void onCreate(Bundle icicle) {
		showActiveOnly = this.getIntent().getBooleanExtra("showActiveOnly",false);
		if(showActiveOnly) {
			this.setTheme(R.style.Theme_TransparentDialog);
			title = "Search Results";
			this.setTitle(title);
		}
		super.onCreate(icicle);
		dsmResourceManager = DsmResourceManager.getDsmResourceManager((OsmandApplication)getApplication());
		ListView lv = getListView();
		if(showActiveOnly) {
			baseList = new HashMap<String,DsmMapDownload>();
			ArrayList<String> ll = this.getIntent().getStringArrayListExtra("maplist");
			for(String dsmMapId : ll) {
				DsmMapDownload map = DsmResourceManager.getDsmResourceManager((OsmandApplication)getApplication()).getDmd(dsmMapId);
				if(map != null)
					baseList.put(dsmMapId,map);
			}
			lv.setBackgroundColor(Color.TRANSPARENT);
		}
		lv.setTextFilterEnabled(true);	
		lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		DsmMapDownload.addListener(this);
		addDsmMap(null);
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(baseList != null)
			baseList.clear();
		DsmMapDownload.removeListener(this);
	}
	@Override
	protected void onListItemClick(final ListView l, View v, final int position, long id) {
	    final CheckedTextView check = (CheckedTextView)v;
	    check.setChecked(!check.isChecked());
	    try {
			final DsmMapDownload map = dsmResourceManager.getDmd(((MapListItem)getListView().getItemAtPosition(position)).dsmMapId);
			if(check.isChecked()) {
				new Thread(new Runnable(){
					@Override
					public void run() {
						final boolean shown = dsmResourceManager.showDsmMap(map);
						
						if(!shown) {
							SearchDSMActivity.this.runOnUiThread(new Runnable(){
								@Override
								public void run() {
									l.setItemChecked(position,false);
								}});	
						} else {
							try {
								if(!showActiveOnly)
									DsmResourceManager.getMapActivity().setDsmMapDownloadViewable(map);
							} catch (Throwable e) {}
						}
					}}).start();
				
			} else {
				dsmResourceManager.hideMap(map);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private class MapListItem implements Comparable<MapListItem> {
		String name;
		String dsmMapId;
		MapListItem(DsmMapDownload dmd) {
			this.name = dmd.toString();
			this.dsmMapId = dmd.getMap().getDsmMapId();
		}
		@Override
		public String toString() {
			return name;
		}
		@Override
		public int compareTo(MapListItem another) {
			return this.name.compareToIgnoreCase(another.name);
		}
	}
	
	@Override
	public synchronized void addDsmMap(DsmMapDownload dsmMapDownload) {
		DsmMapDownload.removeListener(this);
		try {
			final List<MapListItem> data = new ArrayList<MapListItem>();
			Collection<DsmMapDownload> startlist;
			if(!showActiveOnly) {
				startlist = new Vector<DsmMapDownload>(dsmResourceManager.getDsmMaps());
			} else {
				this.setTitle(title);
				if(dsmMapDownload != null) {
					if(!baseList.containsKey(dsmMapDownload.getMap().getDsmMapId()))
						baseList.put(dsmMapDownload.getMap().getDsmMapId(),dsmMapDownload);
				}
				startlist = baseList.values();
			}			
			for(DsmMapDownload map : startlist) {
				data.add(new MapListItem(map));
			}
			Collections.sort(data);
			this.runOnUiThread(new Runnable(){

				@Override
				public void run() {
					int layout = android.R.layout.simple_list_item_checked;
					if(showActiveOnly)
						layout = R.layout.simple_list_item_checked;
					setListAdapter(new ArrayAdapter<MapListItem>(SearchDSMActivity.this,layout,data));
					final ListView lv = getListView();
					for(int x=0; x<lv.getAdapter().getCount(); x++) {
						if(dsmResourceManager.mapActive.contains(((MapListItem)getListView().getItemAtPosition(x)).dsmMapId)) {
							lv.setSelection(x);
							lv.setSelected(true);
							lv.setItemChecked(x,true);
						}
					}
					if(showActiveOnly) {
						lv.invalidate();
					}
				}});
		} catch (Throwable e) {
			e.printStackTrace();
		}
		DsmMapDownload.addListener(this);		
	}
	@Override
	public void removeDsmMap(String dsmMapId) {
		if(showActiveOnly) {
			baseList.remove(dsmMapId);
		}
		addDsmMap(null);
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.dsm_search_menu, menu);
		return true;
	}
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.dsm_search_menu_delete) {
			ListView lv = getListView();
			SparseBooleanArray checked = lv.getCheckedItemPositions();
			ArrayList<String> idstodelete = new ArrayList<String>();
			for(int x =0 ;x<checked.size();x++) {
				if(checked.valueAt(x)) {
					idstodelete.add(((MapListItem)getListView().getItemAtPosition(checked.keyAt(x))).dsmMapId);
				}
			}
			for(String dsmMapId : idstodelete) {
				dsmResourceManager.deleteMapCache(dsmMapId);
			}
			removeDsmMap(null);
		} else if (item.getItemId() == R.id.dsm_search_menu_delete_all) {
			dsmResourceManager.deleteMapCache();
			removeDsmMap(null);			
		} else if (item.getItemId() == R.id.dsm_search_menu_update) {
			ListView lv = getListView();
			SparseBooleanArray checked = lv.getCheckedItemPositions();
			for(int x =0 ;x<checked.size();x++) {
				if(checked.valueAt(x)) {
					if(OsmandSettings.isInternetConnectionAvailable(DsmResourceManager.getApplicationContext()) && OsmandSettings.isUsingInternetToDownloadTiles(OsmandSettings.getPrefs(DsmResourceManager.getApplicationContext()))) {
						try {
							String dsmMapId = ((MapListItem)getListView().getItemAtPosition(checked.keyAt(x))).dsmMapId;
							dsmResourceManager.deleteMapCache(dsmMapId);
							new DsmMapDownload(dsmMapId,true,SearchDSMActivity.this,true);
						} catch (Exception e) {
							Toast.makeText(SearchDSMActivity.this,"Map download failed.",Toast.LENGTH_LONG).show();
						}
					} else {
						Toast.makeText(SearchDSMActivity.this,"Your internet is unavailable or you have disallowed it's use.",Toast.LENGTH_LONG).show();
					}
				}
			}
		} else if (item.getItemId() == R.id.dsm_search_menu_cache_tiles) {
			Map<String, String> entriesMap = SettingsActivity.getTileSourceEntries(this);
			Builder builder = new AlertDialog.Builder(this);
			String[] items = new String[entriesMap.size()];
			if(selectedMaps == null) {
				selectedMaps = new boolean[entriesMap.size()];
				for(int i=0;i<selectedMaps.length;i++)
					selectedMaps[i] = false;
			}
			int i = 0;
			for(String it : entriesMap.values()){
				items[i++] = it;
			}
			builder.setMultiChoiceItems(items, selectedMaps, new DialogInterface.OnMultiChoiceClickListener(){

				@Override
				public void onClick(DialogInterface dialog, int which,
						boolean isChecked) {
					selectedMaps[which] = isChecked;					
				}
				
				
			});
			builder.setPositiveButton("Download Map Tiles", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					ListView lv = getListView();
					SparseBooleanArray checked = lv.getCheckedItemPositions();
					for(int x =0 ;x<checked.size();x++) {
						if(checked.valueAt(x)) {
							final String dsmMapId = ((MapListItem)getListView().getItemAtPosition(checked.keyAt(x))).dsmMapId;
							new Thread(new Runnable() {

								@Override
								public void run() {
									dsmResourceManager.cacheTiles(dsmMapId,selectedMaps.clone());
								}}).start();
						}
					}
					dialog.dismiss();
				}
			});
			builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();					
				}
			});
			builder.show();
		} else if (item.getItemId() == R.id.dsm_search_menu_hide_all) {
			DsmResourceManager.getDsmResourceManager((OsmandApplication)this.getApplicationContext()).hideAllMaps();
			addDsmMap(null);
		}
		return true;
	}
	private boolean[] selectedMaps;
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
	  super.onConfigurationChanged(newConfig);
	  this.addDsmMap(null);
	}
}
